package net.muchine.test.ddd.repository.hibernate;

import java.util.HashSet;
import java.util.Set;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import net.muchine.test.ddd.domain.Customer;
import net.muchine.test.ddd.domain.order.Order;
import net.muchine.test.ddd.repository.OrderRepository;

@Component
public class HibernateOrderRepository implements OrderRepository {
	@Autowired private SessionFactory factory;
	
	public void save(Order order) {
		this.factory.getCurrentSession().save(order);
	}

	public Order delete(String orderId) {
		Order order = this.find(orderId);
		
		this.factory.getCurrentSession().delete(order);
		return null;
	}
	
	public Order find(String orderId) {
		Query query = this.factory.getCurrentSession().createQuery("from Order where orderId=:id")
						.setString("id", orderId);
		Order order = (Order) query.uniqueResult();
		
		return order;
	}

	@SuppressWarnings("unchecked")
	public Set<Order> findByCustomer(Customer customer) {
		Query query = this.factory.getCurrentSession().createQuery("from Order where customer=:customer")
						.setParameter("customer", customer);
		return new HashSet<Order>(query.list());
	}

	@SuppressWarnings("unchecked")
	public Set<Order> findAll() {
		Query query = this.factory.getCurrentSession().createQuery("from Order");
		return new HashSet<Order>(query.list());
	}
}
